package com.homedo.async.mysql.support.prepare.delete;

import com.blinkfox.zealot.bean.SqlInfo;
import com.blinkfox.zealot.core.ZealotKhala;
import com.homedo.async.mysql.support.meta.EntityMetaData;
import com.homedo.async.mysql.support.prepare.util.CollectRecordColumnValUtil;
import com.homedo.plainly.logger.Logger;
import com.homedo.plainly.logger.LoggerFactory;

import java.util.Iterator;
import java.util.Map;

/**
 * @author jgshun
 * @date 2020/3/5 1:56 PM
 */
public abstract class Records2Sql4Delete {
    private static final Logger _LOGGER = LoggerFactory.getLogger(Records2Sql4Delete.class);


    public static <T> Object[] prepare(EntityMetaData<T> entityMetaData, Iterable<T> records, boolean includeNullVals) {
        Object[] prepareSelectSql = new Object[2];

        ZealotKhala sqlKhala = ZealotKhala.start()
                .deleteFrom(entityMetaData.getTableName());

        boolean isFirstLoop = true;//第一个循环
        boolean isFirstCond = true;//第一个条件

        Iterator<T> recordIterator = records.iterator();

        while (recordIterator.hasNext()) {

            if (isFirstLoop) {
                sqlKhala.where(" ");
                isFirstLoop = false;
            }

            T record = recordIterator.next();

            Map<String, Object> columnNameValMap = CollectRecordColumnValUtil.collect(record, entityMetaData, includeNullVals);

            if (!columnNameValMap.isEmpty()) {

                if (isFirstCond) {
                    sqlKhala.text(" ( ");
                    isFirstCond = false;
                } else {
                    sqlKhala.text(" or ( ");
                }

                Iterator<Map.Entry<String, Object>> columnNameValIterator = columnNameValMap.entrySet().iterator();

                boolean isFirstArg = true;//第一个参数

                while (columnNameValIterator.hasNext()) {
                    Map.Entry<String, Object> columnNameValEntry = columnNameValIterator.next();
                    String columnName = columnNameValEntry.getKey();
                    Object columnVal = columnNameValEntry.getValue();

                    if (isFirstArg) {
                        sqlKhala.equal(columnName, columnVal);
                        isFirstArg = false;
                    } else {
                        sqlKhala.andEqual(columnName, columnVal);
                    }
                }

                sqlKhala.text(" ) ");
            }

        }

        SqlInfo sqlInfo = sqlKhala.end();

        prepareSelectSql[0] = sqlInfo.getSql();
        prepareSelectSql[1] = sqlInfo.getParams();

        if (sqlInfo.getParams() == null || sqlInfo.getParams().size() == 0) {
            _LOGGER.error("[缺少删除条件，禁止全表删除操作：{}]", sqlInfo.getSql());
            throw new RuntimeException("[缺少删除条件，禁止全表删除操作]");
        }

        return prepareSelectSql;
    }

}

